//
//  ReturnDetailViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/7/3.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit

class ReturnDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var orderId: String!
    
    @IBOutlet weak var detailTable: UITableView!
    @IBOutlet weak var payTable: UITableView!
    @IBOutlet weak var totalFeeLabel: UILabel!
    @IBOutlet weak var payableFeeLabel: UILabel!
    @IBOutlet weak var couponButton: UIButton!
    @IBOutlet weak var payPageInfo: UILabel!
    @IBOutlet weak var benefitFeeLabel: UILabel!
    
    private var detail: Order.ReturnDetail?
    private var paySwithData = [Order.PaySwith.Method]()
    
    var needAccoundPay = 100
    
    var couponId: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addObserve()
        
        if let app = UIApplication.shared.delegate as? AppDelegate {
            app.payblock(temp: { [weak self] response in
                guard let p = self?.selectedPayment() else {
                    return
                }
                
                if p == .aliPay {
                    if let value = response as? [AnyHashable : AnyObject]{
                        if value["resultStatus"] as! String == "9000"{
                            XHProgressHUD.showSuccess("支付成功")
                            self?.navigationController?.popToRootViewController(animated: true)
                        }else{
                            XHProgressHUD.showError("你取消了支付")
                        }
                    }
                } else if p == .wePay {
                    let model = response as! BaseResp
                    if model.errCode == -2 {
                        XHProgressHUD.showError("你已取消支付")
                    } else {
                        XHProgressHUD.showSuccess("支付成功")
                        self?.navigationController?.popToRootViewController(animated: true)
                    }
                }
            })
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        
        let group = DispatchGroup()
        
        JZLoading.showLoadingWith(toView: self.view)
        
        group.enter()
        Order.returnDetail(orderId: orderId, couponId: couponId ,success: { [weak self] data in
            group.leave()
            
            if let self = self {
                self.detail = data
                self.payPageInfo.text = self.slipViewController?.config?.payPageInfo
                self.benefitFeeLabel.text = self.detail?.benefitFee
                self.totalFeeLabel.text = self.detail?.totalFee
                self.payableFeeLabel.text = self.detail?.payableFee
                self.detailTable.reloadData()
                self.needAccoundPay = (self.detail?.balanceFlag)!
                self.payTable.isHidden = self.detail?.payableFlag == 0
                
                if let list = self.detail?.couponList, let item = list.first {
                    self.couponButton.setTitle(item.couponName, for: .normal)
                } else {
                    self.couponButton.setTitle("选择", for: .normal)
                }
            }
        }) { [weak self] error in
            group.leave()
            self?.showError(error)
        }
        
        group.enter()
        Order.paySwith(success: { [weak self] data in
            group.leave()
            if let data = data {
                self?.paySwithData = data
                self?.payTable.reloadData()
            }
        }) { [weak self] error in
            group.leave()
            self?.showError(error)
        }
        
        group.notify(queue: .main, execute:{ [weak self] in
            
            if self?.needAccoundPay == 1 {
                //需要余额支付
            } else {
                //不需要支付
                self?.paySwithData.remove(at: 0)
                //删除了以后刷新
                self?.payTable.reloadData()
            }
            JZLoading.hideLoading()
        })
    }
    
    func addObserve () {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.payblock { [weak self] response in
                if let payment = self?.selectedPayment() {
                    switch payment {
                    case .aliPay:
                        //支付宝回调
                        if let value = response as? [AnyHashable : AnyObject] {
                            let code = value["resultStatus"] as? String
                            if code == "9000" {
                                XHProgressHUD.showSuccess("支付成功")
                                self?.performSegue(withIdentifier: "shareSegue", sender: nil)
                            } else {
                                XHProgressHUD.showError("你取消了支付")
                            }
                        }
                    case .wePay:
                        //微信回调
                        if let model = response as? BaseResp {
                            if model.errCode == -2 {
                                XHProgressHUD.showError("你已取消支付")
                            } else {
                                XHProgressHUD.showSuccess("支付成功")
                                self?.performSegue(withIdentifier: "shareSegue", sender: nil)
                            }
                        }
                    case .balance, .ticket:
                        break
                    }
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func selectedPayment() -> Order.Pay.Payment? {
        var payment: Order.Pay.Payment?
        for cell in payTable.visibleCells {
            if let cell = cell as? PayMethodCell {
                if cell.isSelected {
                    payment = cell.type
                }
            }
        }
        return payment
    }
    
    // MARK: - IBAction
    
    @IBAction func back(_ sender: UIButton) {
        navigationController?.popToRootViewController(animated: true)
    }
    
    @IBAction func pay(_ sender: UIButton) {
        
        guard let orderId = orderId else {
            showError("订单号错误")
            return
        }
        
        let p = selectedPayment()
        
        if detail?.payableFlag == 1 && p == nil {
            showError("请选择支付方式")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.pay(orderId: orderId, payment: p, couponId: couponId, location: userLocation, success: { [weak self] data in
            JZLoading.hideLoading()
            guard let self = self else {
                return
            }
            
            if data?.payStatus == 0 {
                self.performSegue(withIdentifier: "shareSegue", sender: nil)
                return
            }
            
            if data?.payStatus == 2 {
                XHProgressHUD.showSuccess("支付成功")
                self.performSegue(withIdentifier: "shareSegue", sender: nil)
                return
            }
            
            if let payStr = data?.payStr {
                if p?.rawValue == 1 {
                    Pay.zhifuPay(payStr: payStr)
                } else if p?.rawValue == 2 {
                    Pay.wechatPay(payStr: payStr)
                } else if p?.rawValue == 4 {
                    Pay.applePay(payStr: payStr, controller: self)
                }
            }
        }) { [weak self] error in
            if error.code == 2011 {
                self?.navigationController?.popToRootViewController(animated: true)
            } else {
                JZLoading.hideLoading()
                self?.showError(error)
            }
        }
    }
    
    @IBAction func selectCoupon(_ sender: UIButton) {
        if self.detail?.couponUseable == 1 {
            performSegue(withIdentifier: "payCouponSegue", sender: nil)
        }
    }
    
    // MARK: - UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == payTable {
            return paySwithData.count
        } else if tableView == detailTable {
            return 7
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell: UITableViewCell
        
        if tableView == payTable {
            cell = tableView.dequeueReusableCell(withIdentifier: "payCell", for: indexPath)
            let item = paySwithData[indexPath.row]
            
            if let cell = cell as? PayMethodCell {
                cell.type = item.payMethod
            }
        } else {
            cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.accessoryType = .none
            cell.imageView?.image = nil
            cell.textLabel?.textColor = UIColor(hexString: "6c6c8d")
            cell.detailTextLabel?.textColor = UIColor(hexString: "0a0b41")
            switch indexPath.row {
            case 0:
                cell.textLabel?.text = "起步费"
                cell.detailTextLabel?.text = detail?.stepFee
            case 1:
                cell.textLabel?.text = "时长费"
                cell.detailTextLabel?.text = detail?.longFee
            case 2:
                cell.textLabel?.text = "里程费"
                cell.detailTextLabel?.text = detail?.mileageFee
            case 3:
                cell.textLabel?.text = "预约加时费"
                cell.detailTextLabel?.text = detail?.overtimeFee
            case 4:
                cell.textLabel?.text = "还车附加费"
                cell.detailTextLabel?.text = detail?.returnAttachFee
            case 5:
                cell.textLabel?.text = "不计免赔"
                cell.detailTextLabel?.text = detail?.noDeductibles
            case 6:
                cell.textLabel?.text = "时长包"
                cell.accessoryType = .disclosureIndicator
                if let name = detail?.durationPackageData.durationPackageName, name.count > 0 {
                    cell.detailTextLabel?.text = name
                } else {
                    cell.detailTextLabel?.text = "选择"
                }
            case 7:
                cell.textLabel?.text = "优惠"
                cell.accessoryType = .disclosureIndicator
                cell.textLabel?.textColor = UIColor(valueRGB: 0xB93238, alpha: 1.0)
                
                if detail?.couponUseable == 1 {
                    
                    if let list = detail?.couponList, let item = list.first {
                        cell.detailTextLabel?.text = item.couponName
                    } else {
                        cell.detailTextLabel?.text = "选择"
                    }
                }

                cell.detailTextLabel?.textColor = UIColor(valueRGB: 0xB93238, alpha: 1.0)
            default:
                break
            }
        }
        
        return cell
    }
    
    // MARK: - UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == payTable {
            for cell in tableView.visibleCells {
                if let cell = cell as? PayMethodCell {
                    cell.setSelected(false, animated: true)
                }
            }
            if let cell = tableView.cellForRow(at: indexPath) as? PayMethodCell {
                cell.setSelected(true, animated: true)
            }
        } else {
            if indexPath.row == 6 {
                performSegue(withIdentifier: "durationPackageSegue", sender: nil)
            }
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "payCouponSegue" {
            if let vc = segue.destination as? PayCouponViewController {
                vc.money = detail?.couponOrderFee
                vc.delegate = self
            }
        } else if segue.identifier == "durationPackageSegue" {
            if let vc = segue.destination as? DurationPackageListViewController {
                vc.orderId = detail?.orderId
                vc.selectedDurationPackageId = detail?.durationPackageData.durationPackageId
                vc.projectTimerentId = detail?.durationPackageData.projectTimerentId
                vc.sourceFlag = 2
                vc.selectedPackageBlock = { id, name in
                    if id != nil {
                        self.couponId = nil
                    }
                }
            }
        } else if segue.identifier == "shareSegue" {
            if let vc = segue.destination as? ShareViewController {
                vc.orderId = orderId
            }
        }
    }
}
